package com.neusoft.elm.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.neusoft.elm.po.Business;
import com.neusoft.elm.service.BusinessService;
import com.neusoft.elm.service.impl.BusinessServiceImpl;

public class BusinessController {

   public Object listBusinessByOrderTypeId(HttpServletRequest request) throws Exception{
       Integer orderTypeId = Integer.valueOf(request.getParameter("orderTypeId"));
       BusinessService service = new BusinessServiceImpl();
       List<Business> list= service.listBusinessByOrderTypeId(orderTypeId);
       return list;
   }
   
   public Object getBusinessById(HttpServletRequest request) throws Exception{
       Integer businessId = Integer.valueOf(request.getParameter("businessId"));
       BusinessService service = new BusinessServiceImpl();
       Business business = service.getBusinessById(businessId);
       return business;
   }
   
   public Object saveBusiness(HttpServletRequest request) {
	    try {
	        Business business = new Business();
	        // 设置业务属性...
	        business.setBusinessName(request.getParameter("businessName"));
	        business.setPassword(request.getParameter("password"));
	        business.setBusinessAddress(request.getParameter("businessAddress"));
	        business.setBusinessExplain(request.getParameter("businessExplain"));
	        business.setBusinessImg(request.getParameter("businessImg"));
	        business.setOrderTypeId(Integer.parseInt(request.getParameter("orderTypeId")));
	        business.setStarPrice(Double.parseDouble(request.getParameter("starPrice")));
	        business.setDeliveryPrice(Double.parseDouble(request.getParameter("deliveryPrice")));
	        business.setRemarks(request.getParameter("remarks"));
	        
	        BusinessService service = new BusinessServiceImpl();
	        int businessId = service.saveBusiness(business);
	        
	        // 创建包含ID的成功响应
	        Map<String, Object> response = new HashMap<>();
	        response.put("success", true);
	        response.put("businessId", businessId);
	        response.put("message", "商家注册成功");
	        
	        return response;
	    } catch (Exception e) {
	        // 错误响应
	        Map<String, Object> error = new HashMap<>();
	        error.put("success", false);
	        error.put("message", "注册失败: " + e.getMessage());
	        
	        return error;
	    }
	}
   
   
   public Object businessLogin(HttpServletRequest request) throws Exception {
       Integer businessId = Integer.valueOf(request.getParameter("businessId"));
       String password = request.getParameter("password");
       
       BusinessService service = new BusinessServiceImpl();
       return service.getBusinessByIdAndPassword(businessId, password);
   }
   
   public Object updateBusiness(HttpServletRequest request) {
	    try {
	        // 获取商家ID
	        int businessId = Integer.parseInt(request.getParameter("businessId"));
	        
	        // 从数据库加载原始商家数据
	        BusinessService tempService = new BusinessServiceImpl();
	        Business originalBusiness = tempService.getBusinessById(businessId);
	        
	        if (originalBusiness == null) {
	            return createErrorResponse("未找到商家信息");
	        }
	        
	        // 创建更新对象
	        Business updatedBusiness = new Business();
	        updatedBusiness.setBusinessId(businessId);
	        
	        // 设置更新字段
	        updatedBusiness.setBusinessName(getUpdatedValue(request, "businessName", originalBusiness.getBusinessName()));
	        updatedBusiness.setBusinessAddress(getUpdatedValue(request, "businessAddress", originalBusiness.getBusinessAddress()));
	        updatedBusiness.setBusinessExplain(getUpdatedValue(request, "businessExplain", originalBusiness.getBusinessExplain()));
	        updatedBusiness.setRemarks(getUpdatedValue(request, "remarks", originalBusiness.getRemarks()));
	        
	        String newPassword = request.getParameter("password");
	        if (newPassword != null && !newPassword.trim().isEmpty()) {
	            // 有新密码则使用新密码
	            updatedBusiness.setPassword(newPassword);
	            System.out.println("使用新密码");
	        } else {
	            // 确保原密码不为null
	            if (originalBusiness.getPassword() == null) {
	                throw new Exception("原密码不能为null");
	            }
	            updatedBusiness.setPassword(originalBusiness.getPassword());
	            System.out.println("使用原密码: " + originalBusiness.getPassword());
	        }
	        
	        // 处理图片更新
	        String newImage = request.getParameter("businessImg");
	        if (newImage != null && !newImage.isEmpty()) {
	            updatedBusiness.setBusinessImg(newImage);
	        } else {
	            updatedBusiness.setBusinessImg(originalBusiness.getBusinessImg());
	        }
	        
	        // 处理数值字段
	        updatedBusiness.setOrderTypeId(getUpdatedInt(request, "orderTypeId", originalBusiness.getOrderTypeId()));
	        updatedBusiness.setStarPrice(getUpdatedDouble(request, "starPrice", originalBusiness.getStarPrice()));
	        updatedBusiness.setDeliveryPrice(getUpdatedDouble(request, "deliveryPrice", originalBusiness.getDeliveryPrice()));
	        
	        System.out.println("更新商家信息: " + updatedBusiness);
	        
	        // 执行更新
	        BusinessService service = new BusinessServiceImpl();
	        int result = service.updateBusiness(updatedBusiness);
	        
	        // 创建响应
	        Map<String, Object> response = new HashMap<>();
	        if (result > 0) {
	            response.put("success", true);
	            response.put("message", "商家信息更新成功");
	            
	            // 返回更新后的完整商家信息
	            Business fullUpdated = service.getBusinessById(businessId);
	            response.put("business", fullUpdated);
	        } else {
	            response.put("success", false);
	            response.put("message", "商家信息更新失败，请重试");
	        }
	        return response;
	    } catch (Exception e) {
	        System.err.println("更新商家信息错误: " + e.getMessage());
	        e.printStackTrace();
	        return createErrorResponse("更新失败: " + e.getMessage());
	    }
	}

	// 添加错误响应创建方法
	private Map<String, Object> createErrorResponse(String message) {
	    Map<String, Object> error = new HashMap<>();
	    error.put("success", false);
	    error.put("message", message);
	    return error;
	}

	// 辅助方法：获取更新值或保留原始值
	private String getUpdatedValue(HttpServletRequest request, String paramName, String originalValue) {
	    String value = request.getParameter(paramName);
	    return (value != null && !value.trim().isEmpty()) ? value : originalValue;
	}

	private int getUpdatedInt(HttpServletRequest request, String paramName, int originalValue) {
	    String value = request.getParameter(paramName);
	    try {
	        return (value != null && !value.trim().isEmpty()) ? Integer.parseInt(value) : originalValue;
	    } catch (NumberFormatException e) {
	        return originalValue;
	    }
	}

	private double getUpdatedDouble(HttpServletRequest request, String paramName, double originalValue) {
	    String value = request.getParameter(paramName);
	    try {
	        return (value != null && !value.trim().isEmpty()) ? Double.parseDouble(value) : originalValue;
	    } catch (NumberFormatException e) {
	        return originalValue;
	    }
	}
   
   
}
